#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time   : 2021/7/4 20:31
# @Author : cjw
import os

from appium import webdriver

from app_wework_po.base.base_page import BasePage
from app_wework_po.page.main_page import MainPage
from app_wework_po.setting import DES_CAPS
from app_wework_po.util.file_operator import YmlOperator
from app_wework_po.util.log import logger
from app_wework_po.setting import IMPLICITLY_WAIT, COMMAND_EXECUTOR_IP


class BaseApp(BasePage):
    """app相关操作：启动、关闭、重启"""

    def start(self):
        """应用启动"""
        if not self.driver:
            logger.info('开始初始化操作，创建driver，建立session会话')
            des_caps = YmlOperator(DES_CAPS).data  # 获取启动参数
            device_name = os.getenv('device')  # 获取设备名称
            port = os.getenv('port')  # 获取服务启动端口

            # 设备和启动端口判断
            caps = {}
            if device_name:
                device_name = device_name.lower()
                if device_name == 'p20':
                    caps = des_caps['huawei_p20']
            else:
                caps = des_caps['simulator_ys']
            port = port if port else '4723'

            try:
                self.driver = webdriver.Remote(f'{COMMAND_EXECUTOR_IP}:{port}/wd/hub', caps)
                self.driver.implicitly_wait(IMPLICITLY_WAIT)
            except Exception as ex:
                logger.error(f'启动app失败，报错信息：{ex}')
                raise ex
        else:
            # launch_app(): 本机启动driver中app
            # start_activity：指定app_package和app_activity本机启动app
            logger.info('复用driver, 启动app')
            self.driver.launch_app()

        return self

    def restart(self):
        """app重启"""
        logger.info('app重启')
        self.driver.close_app()
        self.driver.launch_app()

    def close_app_back(self, num: int = 5):
        """
        通过back操作，关闭app
        :param num:
        :return:
        """
        logger.info('通过back操作，关闭app')
        for i in range(num):
            self.driver.back()

    def close_app(self):
        """关闭app"""
        logger.info('关闭app')
        self.driver.close_app()

    def quit(self):
        """关闭session"""
        logger.info('关闭创建的session会话')
        self.driver.quit()

    def goto_main(self):
        """进入主页入口"""
        return MainPage(self.driver)
